package com.cetc.ga.httpclient;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

//import net.sf.json.JSONObject;

/**
 * 
 * @author zc
 * @date 2019-02-21
 */
public class HttpUtils {

	public static void main(String[] args) {
        String url = "http://localhost:8080/user/person";
        //String url = "http://localhost:8080/user/testJson";
	    //Map<String, String> paramMap = new HashMap<>();
        //paramMap.put("cardId","230306198610245317");
        //paramMap.put("token","123456");

        //String paramstring = JSONObject.fromObject(paramMap).toString();
        //String _result = httpGetRequest(url, paramMap);
        //String _result = httpPostRequest(url, paramMap);

        //String _result = httpPostRequestJson(url, paramMap);

        String _result = httpGetRequest(url);
        System.out.println(_result);
	}

    /**
     * Http Client封装的Https请求
     * @param requestType 请求方法，有 OPTIONS、GET、HEAD、POST、PUT、DELETE、TRACE、CONNECT 这几种
     * @param contentType 提交数据的方式
     * @param url 请求目标url  http://ip:port/xxx
     * @param paramMap 请求参数
     * @param headers 请求头
     * @return 返回请求的结果
     */
    public static String httpRequest(String requestType, String contentType, String url, Map<String, String> paramMap, Map<String, String> headers) {
        String _result = "";
        /**
         * HTTP/1.1 协议规定的 HTTP 请求方法有 OPTIONS、GET、HEAD、POST、PUT、DELETE、TRACE、CONNECT 这几种。
         * requestType
         */
        switch (requestType) {
            case "GET":
                _result = httpGetRequest(url, paramMap);
                break;
            case  "POST":
                /**
                 * POST 一般用来向服务端提交数据，POST 提交数据的常见4种方式。
                 */
                if(contentType.equals("application/x-www-form-urlencoded")) {
                    // 补充

                }else if(contentType.equals("multipart/form-data")) {
                    // 补充

                }else if(contentType.equals("application/json")) {
                    _result = httpPostRequestJson(url,paramMap, headers);
                }else if(contentType.equals("text/xml")) {
                    // 补充

                }else {  // 后面有的话继续补充
                    //System.out.println("");
                    _result = httpPostRequest(url, paramMap);
                }
                break;
            case "PUT":
                // 补充
                break;
            case "DELETE":
                // 补充
                break;
            case "OPTIONS":
                // 补充
                break;
            case "HEAD":
                // 补充
                break;
            case "TRACE":
                // 补充
                break;
            case "CONNECT":
                // 补充
                break;
            default:
                System.out.println("请求方法不对！！！ HTTP/1.1 协议规定的 HTTP 请求方法有 OPTIONS、GET、HEAD、POST、PUT、DELETE、TRACE、CONNECT 。");
                break;
        }
        return _result;
    }

    /**
     * GET
     */

	/**
	 * HttpClient封装的Http请求， 请求方法GET
	 * @param urlstring 请求目标url  http://ip:port/xxx
	 * @param paramMap 请求参数
	 * @return
	 */
	public static String httpGetRequest(String urlstring, Map<String, String> paramMap) {
		String paramstring = "";
    	for(Entry<String, String> entry : paramMap.entrySet()) {
    		paramstring += entry.getKey() + "=" + entry.getValue() + "&";
    	}
    	paramstring = paramstring.substring(0, paramstring.length()-1);
    	urlstring += "?" + paramstring;
    	//System.out.println(paramstring);
        return httpGetRequest(urlstring);
	}

    /**
     * HttpClient封装的Http请求， 请求方法GET
     * @param urlstring 请求目标url ,http://ip:port/xxx
     * @param params
     *      请求参数，请求参数应该是
     *      "name1=value1"
     *      "name2=value2"
     *      的形式。
     * @return
     */
    public static String httpGetRequest(String urlstring, String... params) {
        String param = packageParam(params);
        urlstring += "?" + param;
        return httpGetRequest(urlstring);
    }
	
	/**
	 * HttpClient封装的Http请求， 请求方法GET
	 * @param urlstring 请求目标url ,包括请求参数 http://ip:port/xxx?param1=""&param2=""
	 * @return
	 */
	public static String httpGetRequest(String urlstring) {
		//urlstring += "?" + paramstring;
		HttpURLConnection connection = null;
        try {
            URL url = new URL(urlstring);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            
            // get response
            InputStream is = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuffer response = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
                response.append("\t");
            }
            reader.close();
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
	}

    /**
     * POST
     */

    /**
     * HttpClient封装的Http请求， 请求方法Post
     * @param urlstring  请求目标url
     * @param paramMap  请求参数
     * @return
     */
    public static String httpPostRequest(String urlstring, Map<String, String> paramMap) {
        //String paramstring = JSONObject.fromObject(paramMap).toString();
    	
    	String paramstring = "";
    	for(Entry<String, String> entry : paramMap.entrySet()) {
    		paramstring += entry.getKey() + "=" + entry.getValue() + "&";
    	}
    	paramstring = paramstring.substring(0, paramstring.length()-1);
    	urlstring += "?" + paramstring;
    	//System.out.println("url = " + urlstring);
        return httpPostRequest(urlstring);
    }

    /**
     * HttpClient封装的Http请求， 请求方法Post
     * @param urlstring  请求目标url,包括请求参数 http://ip:port/xxx?param1=""&param2=""
     * @return
     */
    public static String httpPostRequest(String urlstring) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlstring);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");

            connection.setRequestProperty("charset", "UTF-8");
            connection.setUseCaches(false);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(1000); 
            // send request
            /*
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            // wr.writeBytes(paramstring);
            wr.write(paramstring.getBytes());
            //  wr.write(new String(paramstring.getBytes("GBK"),"UTF-8").replaceAll("\"", "'").getBytes());
            //wr.writeChars(paramstring);
           
            wr.flush();
            wr.close();
            */
            // get response
            InputStream is = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuffer response = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
                response.append("\t");
            }
            reader.close();
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * HttpClient封装的Http请求， 请求方法Post
     * @param urlstring 请求目标url
     * @param paramMap 请求参数,    JSONObject字符串
     * @return
     */
    public static String httpPostRequestJson(String urlstring, Map<String, String> paramMap) {
        //JSONObject.fromObject(paramMap).toString();
        String paramstring = JSONObject.toJSONString(paramMap);
        //System.out.println(paramstring);
        //return "";
    	return httpPostRequestJson(urlstring, paramstring);
    }

    /**
     * HttpClient封装的Http请求， 请求方法Post
     * @param urlstring 请求目标url
     * @param paramstring 请求参数, JSON字符串
     * @return
     */
    public static String httpPostRequestJson(String urlstring, String paramstring) {
    	HttpURLConnection connection = null;
        try {
            URL url = new URL(urlstring);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

            connection.setRequestProperty("charset", "UTF-8");
            connection.setUseCaches(false);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(1000); 
            // send request
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            // wr.writeBytes(paramstring);
            //wr.write(paramstring.getBytes());
            //wr.write(new String(paramstring.getBytes("GBK"),"UTF-8").replaceAll("\"", "'").getBytes());
            wr.write(new String(paramstring.getBytes("GBK"),"UTF-8").getBytes());
            //wr.writeChars(paramstring);
           
            wr.flush();
            wr.close();
         
            // get response
            InputStream is = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuffer response = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
                response.append("\t");
            }
            reader.close();
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * HttpClient封装的Http请求， 请求方法Post
     * @param urlstring 请求目标url
     * @param paramMap 请求参数
     * @param headers 请求头
     * @return
     */
    public static String httpPostRequestJson(String urlstring,  Map<String, String> paramMap, Map<String, String> headers) {
        String paramstring = JSONObject.toJSONString(paramMap);
        return httpPostRequestJson(urlstring, paramstring, headers);
    }

	/**
	 * HttpClient封装的Http请求， 请求方法Post
	 * @param urlstring  请求目标url
	 * @param paramstring  请求参数
	 * @param headers  请求头
	 * @return
	 */
	public static String httpPostRequestJson(String urlstring, String paramstring, Map<String, String> headers) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlstring);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            connection.setRequestProperty("charset", "UTF-8");
            if (headers != null) {
                for (Entry<String, String> header : headers.entrySet()) {
                    connection.setRequestProperty(header.getKey(), header.getValue());
                }
            }

            connection.setUseCaches(false);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(1000);
            // send request
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            // wr.writeBytes(paramstring);
            wr.write(paramstring.getBytes());
            wr.flush();
            wr.close();
            // get response
            InputStream is = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuffer response = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
                response.append("\t");
            }
            reader.close();
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将参数封装成我们需要的形式
     * @param params
     *   参数形式是
     *   name1=value1
     *   name2=value2
     * @return 返回的请求参数应该是 name1=value1&name2=value2的形式
     */
    private static String packageParam(String[] params) {
        String pre = "_zcargs";
        String param = "";
        int k = 0;
        for(int i=0; i<params.length; i++) {
            if(params[i].contains("=")) {
                if(countChar(params[i],'=') == 1 ) {
                    if(params[i].indexOf('=') == 0)
                        param += pre + (k++) + params[i] + "&";
                    else
                        param += params[i] + "&";
                } else {
                    param += params[i] + "&";
                }
            } else {
                param += pre + (k++) + "=" + params[i] + "&";
            }
        }
        param = param.substring(0, param.length()-1);
        return param;
    }

    /**
     * 计数某个字符在字符串中出现的次数
     * @param str 字符串
     * @param ch 字符
     * @return  某个字符在字符串中出现的次数
     */
    private static int countChar(String str,char ch) {
        // 将字符串转换为字符数组
        char[] chs = str.toCharArray();
        // 定义变量count存储字符串出现次数
        int count = 0;
        for(int i = 0;i < chs.length;i++) {
            if(chs[i] == ch) {
                count++;
            }
        }
        return count;
    }

}
